What is the output of the following code snippet?var x = 5;function fo...
The variable x is declared inside the function foo using "var," which creates a local scope. At the time of the first console.log statement, the variable x exists but has not been assigned a value yet, resulting in undefined.
View all questions of this test
What is the output of the following code snippet?var x = 5;function fo...
Explanation:
The output of the code snippet will be undefined.
Code Explanation:
1. The variable x is declared and assigned the value 5.
2. The function foo() is defined.
3. Inside the function foo(), a local variable x is declared using the var keyword. This creates a new variable x that is local to the function scope.
4. The console.log() statement is executed, which tries to print the value of the local variable x. However, at this point in the code, the local variable x is declared but not yet initialized, so its value is undefined.
5. The local variable x is assigned the value 10.
6. The execution of the function foo() is complete.
7. The function foo() is called, which triggers the execution of the code inside the function.
8. Since the variable x is declared and initialized within the function scope, it is treated as a separate variable from the global variable x.
9. When the console.log() statement tries to print the value of the local variable x, its value is undefined because it is declared but not yet initialized.
10. Therefore, the output of the code snippet is undefined.
Key Points:
- When a variable is declared using the var keyword inside a function, it is hoisted to the top of the function scope.
- However, the initialization of the variable is not hoisted, so at the point where the console.log() statement is executed, the variable is declared but not yet initialized, resulting in undefined as the output.
- It is good practice to declare variables at the top of their scope to avoid confusion and unexpected results.